package leaveSystem.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import leaveSystem.bizlogic.LeaveManager;
import leaveSystem.dao.mysql.EmployeeDAOImpl;
import leaveSystem.model.Employee;

import java.util.List;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public LoginServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Login(request, response);
	}

	protected void Login(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {

			/*Employee user = new Employee();
			user.setUsername(request.getParameter("username"));
			user.setPassword(request.getParameter("password"));
			

			LeaveManager manager = new LeaveManager();
			manager.LoginManager(user);
			if (user.isValid()) {
				

				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser", user);
				session.setAttribute("roleId", user.getRoleId());
				response.sendRedirect("ApplyLeaveForm.jsp"); // logged-in page

			} else {

				request.setAttribute("errorMessage",
						"Invalid username or password");
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/Login.jsp");
				dispatcher.forward(request, response);
			}*/
			//new one
			Employee user = new Employee();
			user.setUsername(request.getParameter("username").trim());
			user.setPassword(request.getParameter("password").trim());

			LeaveManager manager = new LeaveManager();
			List<Employee> loginUser = manager.checkEmployeeLogin(user);
			if (loginUser.size()==1) {				

				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser", loginUser.get(0));
				response.sendRedirect("welcome.jsp"); // logged-in page

			} else {

				request.setAttribute("errorMessage","Invalid username or password");
				RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
				dispatcher.forward(request, response);
			}
			
		}

		catch (Throwable theException) {
			System.out.println(theException);
		}
	}
}

